import Vue from "vue";
import Vuex from "vuex";
import { playlistDetail } from "@/apis/songOrder";
import Message from "ant-design-vue/lib/message";
import {
  phoneLogin,
  logout,
  loginQrKey,
  loginQrCreate,
  loginQrCheck,
  loginRefresh,
} from "@/apis/user";
import { playMode, playModeText, playModeList } from "@/common/cantas";

Vue.use(Vuex);
const files = require.context("./modules", false, /\.js$/);
const modules = {};

files.keys().forEach((key) => {
  modules[key.replace(/(\.\/|\.js)/g, "")] = files(key).default;
});
Object.keys(modules).forEach((key) => {
  modules[key]["namespaced"] = true;
});
const store = new Vuex.Store({
  modules,
  state: {
    globalLoading: false,
    globalMsgShow: false,
    globalMsg: {
      type: "",
      msg: "",
    },
    playListShow: false,
    electronStore: {
      playList: [],
      playMode: playMode.listPlay,
      currentPlaylistIndex: 0,
      currentSong: {
        id: "",
        isLocal: false,
        name: "",
        picUrl: "",
        singer: [],
        url: "",
        time: 0,
      },
      logininfo: {
        account: {},
        bindings: {},
        cookie: "",
        profile: {},
        token: "",
      },
    },
    playStatus: false, // false暂停
    volume: !!localStorage.getItem("volume")
      ? Number(localStorage.getItem("volume"))
      : 50,
  },
  actions: {
    async login({ commit }, userParams) {
      if (userParams.type === 1) {
        const res = await phoneLogin(userParams.phone, userParams.password);
        if (res.code === 200) {
          Vue.prototype.$ipc.send("electron-store-set", {
            key: "logininfo",
            value: res,
          });
          commit("setElectronStore", { logininfo: res });
          return true;
        } else {
          Message.error(res.msg || res.message);
          return false;
        }
      }
    },
    async loginRefresh({ commit, dispatch }) {
      const res = await loginRefresh();
      if (res.code === 301) {
        // 需要登录
        dispatch("logOut");
      } else if (res.code === 200) {
        // Vue.prototype.$ipc.send("electron-store-set", {
        //   key: "logininfo",
        //   value: res,
        // });
        // commit("setElectronStore", { logininfo: res });
      }
    },
    async qrLogin({ commit }) {
      const key = await loginQrKey();
      if (!key) {
        commit("setLoginKey", key);
      }
    },
    async logOut({ commit }) {
      const res = await logout();
      if (res.code === 200) {
        const init = {
          logininfo: {
            account: {},
            bindings: {},
            cookie: "",
            profile: {},
            token: "",
          },
        };
        Vue.prototype.$ipc.send("electron-store-set", {
          key: "logininfo",
          value: init,
        });
        commit("setElectronStore", init);
      }
    },
    // 切换歌曲
    changeSong({ commit }, direction) {
      console.log(direction);
    },

    // 获取歌单详情
    getOrdelDetail({ commit, dispatch }, id) {
      commit("setGlobalLoading", true);
      playlistDetail(id)
        .then((res) => {
          const { code, playlist } = res;
          if (code === 200) {
            const playList = playlist.tracks.map((s) => {
              return {
                id: s.id,
                name: s.name,
                picUrl: s.al.picUrl,
                singer: s.ar,
                time: s.dt,
              };
            });
            Vue.prototype.$ipc.send("electron-store-set", {
              key: "playList",
              value: playList,
            });
            commit("setElectronStore", { playList });
            commit("setCurrentPlaylistIndex", 0);
            // 取出里面歌曲的id和赋值当前音乐信息到组件，并记录当前播放下标
            commit("setCurrentSong", {
              value: playList[0],
              isEmpty: true,
            });
          }
        })
        .catch((err) => {})
        .finally(() => {
          commit("setGlobalLoading", false);
        });
    },
  },
  mutations: {
    setDrawList(state, data) {
      if (data === undefined) {
        state.playListShow = !state.playListShow;
      } else {
        state.playListShow = data;
      }
    },
    setPlayMode(state) {
      const play = state.electronStore.playMode;
      const playModeIndex = playModeList.findIndex((i) => i.value === play);
      state.electronStore.playMode =
        playModeIndex >= playModeList.length - 1
          ? playModeList[0].value
          : playModeList[playModeIndex + 1].value;
    },
    setUserInfo(state, data) {
      state.userToken = data.token;
      state.userAccount = data.account;
      state.userProfile = data.profile;
      state.userCookie = data.cookie;
    },
    setLoginKey(state, data) {
      state.loginKey = data;
    },
    setGlobalLoading(state, value) {
      state.globalLoading = value;
    },
    setCurrentSong(state, { value, isEmpty }) {
      if (value) {
        if (!isEmpty) {
          state.electronStore.currentSong = {
            ...state.electronStore.currentSong,
            ...value,
          };
        } else {
          state.electronStore.currentSong = value;
        }
      }
      Vue.prototype.$ipc.send("electron-store-set", {
        key: "currentSong",
        value: state.electronStore.currentSong,
      });
      console.log(
        state.electronStore.currentSong,
        "state.electronStore.currentSong"
      );
    },
    setVolume(state, value) {
      state.volume = value;
      localStorage.setItem("volume", value);
    },
    setPlayStatus(state, status) {
      if (status === undefined) {
        status = !state.playStatus;
      }
      state.playStatus = status;
    },
    setCurrentPlaylistIndex(state, index) {
      state.electronStore.currentPlaylistIndex = index;
      Vue.prototype.$ipc.send("electron-store-set", {
        key: "currentPlaylistIndex",
        value: index,
      });
    },
    setElectronStore(state, data) {
      state.electronStore = { ...state.electronStore, ...data };
    },
    setGlobalMsgShow(state, data) {
      state.globalMsgShow = data;
    },
    setGlobalMsg(state, data) {
      state.globalMsg = data;
    },
  },
});
export default store;
